package com.ucomm.talent.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.client.HttpResponseException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ucomm.talent.AppConfig;
import com.ucomm.talent.AppConstants;
import com.ucomm.talent.AppException;
import com.ucomm.talent.common.FileUtils;
import com.ucomm.talent.model.HotCompanyInfo;
import com.ucomm.talent.model.JobFairInfo;
import com.ucomm.talent.model.JobOfferInfo;
import com.ucomm.talent.model.NewsInfo;
import com.ucomm.talent.model.RecommendedJobsInfo;
import com.ucomm.talent.model.ResumeInfo;
import com.ucomm.talent.model.TalentsInfo;
import com.vita.bduck.BDuckHttp;
import com.vita.bduck.http.AjaxCallBack;


/**
 * 搜索功能模块业务类
 * Created with IntelliJ IDEA.
 * User: Vita Hao
 * Date: 13-5-29
 * Time: 下午3:52
 * To change this template use File | Settings | File Templates.
 */
public class SearchManager {

    private Context mContext;
    private Handler mHander;
 /*   public SearchManager(Context mContext) {

        this.mContext = mContext;
    }*/

    public SearchManager(Context mContext, Handler mHander) {
        this.mContext = mContext;
        this.mHander = mHander;
    }

    /**
     * 从网络搜索信息
     *
     * @return
     */
    @SuppressWarnings("unchecked")
	public void searchDataFromNetwrok(final String url, final Object... params) {
        BDuckHttp fh = new BDuckHttp();
        fh.get(url, new AjaxCallBack() {

            @Override
            public void onLoading(long count, long current) { //每1秒钟自动被回调一次
                // textView.setText(current+"/"+count);
                Log.i("vita", ">>>>>>>>..onLoading..<<<<<<<<");
            }

            @Override
            public void onSuccess(Object t) {
                //  textView.setText(t==null?"null":t);
                if (t instanceof String) {
                    String data = (String) t;
                    if (url.contains(AppConstants.RECOMMENDED_JOBS)) {
                        Message msg = new Message();
                        try {
                           // saveAreaMap(data,AppConstants.AREA_JSON_KEY);
                            ArrayList<RecommendedJobsInfo> list  = resolveFeaturedJobsJson(data);
                           // ((TextView) params[0]).setText(data);
                            AppConfig.comName = getMapFromJson(data, "com_name");
                            msg.what = AppConstants.MsgStatus.MSG_SUCCUSS;
                            msg.obj = list;
                            mHander.sendMessage(msg);
                        } catch (AppException e) {
                            e.printStackTrace();
                            msg.what = -1;
                            msg.obj = e;
                            mHander.sendMessage(msg);
                        }
                    }else if(url == AppConstants.HOT_SEARCH){
                	    Message msg = new Message();
                	    String[] keyWords=null;
                	    try {
							keyWords= resolveHotKeyJson(data);
							msg.what=AppConstants.MsgStatus.MSG_SUCCUSS;
							msg.obj = keyWords;
							mHander.sendMessage(msg);
						} catch (AppException e) {
							e.printStackTrace();
						    msg.what = -1;
                            msg.obj = e;
                            mHander.sendMessage(msg);
						}
                    }else if(url.contains(AppConstants.JOB_OFFERS) ){
                	    Message msg = new Message();
                	    try {
							ArrayList<JobOfferInfo> jobOfferInfoList = resolveJobOfferInfoJson(data);
							AppConfig.comName = getMapFromJson(data, "com_name");
							msg.what = AppConstants.MsgStatus.MSG_SUCCUSS;
							msg.obj = jobOfferInfoList;
							mHander.sendMessage(msg);
                	    } catch (AppException e) {
							e.printStackTrace();
							msg.what = -1;
	                        msg.obj = e;
	                        mHander.sendMessage(msg);
                	    }
                    }else if(url.contains(AppConstants.HOT_COMPANY)){
                	    Message msg = new Message();
                	    try {
							ArrayList<HotCompanyInfo> hotCompanyInfoList = resolveHotCompanyInfoJson(data);
							msg.what = AppConstants.MsgStatus.MSG_SUCCUSS;
							msg.obj = hotCompanyInfoList;
							mHander.sendMessage(msg);
						} catch (AppException e) {
							e.printStackTrace();
							msg.what = -1;
	                        msg.obj = e;
	                        mHander.sendMessage(msg);
						}
                    }else if(url.contains(AppConstants.JOB_FAIR)){
                	    Message msg = new Message();
                	    try {
		    				ArrayList<JobFairInfo> jobFairInfoList = resolveJobFairInfoJson(data);
		    				msg.what = AppConstants.MsgStatus.MSG_SUCCUSS;
		    				msg.obj = jobFairInfoList;
		    				mHander.sendMessage(msg);
		    			} catch (AppException e) {
		    				e.printStackTrace();
		    				msg.what = -1;
	                        msg.obj = e;
	                        mHander.sendMessage(msg);
		    			}
                    }else if(url.contains(AppConstants.TALENTS)){
                	    Message msg = new Message();
                	    try {
							ArrayList<TalentsInfo> talentsInfoList = resolveTalentsInfoJson(data);
							msg.what = AppConstants.MsgStatus.MSG_SUCCUSS;
							msg.obj = talentsInfoList;
							mHander.sendMessage(msg);
						}catch (AppException e) {
		    				e.printStackTrace();
		    				msg.what = -1;
	                        msg.obj = e;
	                        mHander.sendMessage(msg);
						}
                    }else if(url.contains(AppConstants.JOB_RESUME)){
                	    Message msg = new Message();
                	    try {
	                		ArrayList<ResumeInfo> resumeInfoList = resolveResumeInfoJson(data);
		    				msg.what = AppConstants.MsgStatus.MSG_SUCCUSS;
		    				msg.obj = resumeInfoList;
		    				mHander.sendMessage(msg);
                	    } catch (AppException e) {
		    				e.printStackTrace();
		    				msg.what = -1;
	                        msg.obj = e;
	                        mHander.sendMessage(msg);
                	    }
                    }else if(url.contains(AppConstants.NEWS)){
                	    Message msg = new Message();
                	    try {
	        		    	ArrayList<NewsInfo> newsInfoList = resolveNewsInfoJson(data);
							msg.what = AppConstants.MsgStatus.MSG_SUCCUSS;
							msg.obj = newsInfoList;
							mHander.sendMessage(msg);
                	    } catch (AppException e) {
							e.printStackTrace();
							msg.what = -1;
	                        msg.obj = e;
	                        mHander.sendMessage(msg);
                	    }
                    }else if(url == AppConstants.CATEGORY){
                    	Message msg = new Message();
                    	try {
							String[] categoryInfos = resolveCategoryJson(data);
							
							msg.what = AppConstants.MsgStatus.MSG_SUCCUSS;
							msg.obj = categoryInfos;
							mHander.sendMessage(msg);
						} catch (AppException e) {
							e.printStackTrace();
							msg.what = -1;
							msg.obj = e;
							mHander.sendMessage(msg);
						}
                    }else if(url == AppConstants.CACHE){
                    	//TODO ....
                    	Message msg = new Message();
                    	FileUtils file = new FileUtils();
                    	try {
                    		if(!file.isFileExist("steeltalent")){
                    			HashMap<String, String> jobMap = new HashMap<String, String>();
    							HashMap<String, String> cityMap = new HashMap<String, String>();
    							HashMap<String, String> industryMap = new HashMap<String, String>();
    							HashMap<String, String> comMap = new HashMap<String, String>();
    							HashMap<String, String> userMap = new HashMap<String, String>();
    							cityMap = getMapFromJson(data, "city");
    							jobMap = getMapFromJson(data, "job");
    							industryMap = getMapFromJson(data, "industry");
    							comMap = getMapFromJson(data, "com");
    							userMap = getMapFromJson(data, "user");
    							file.write2SDFromMap("steeltalent", "cityMap", cityMap);
    							file.write2SDFromMap("steeltalent", "jobMap", jobMap);
    							file.write2SDFromMap("steeltalent", "industryMap", industryMap);
    							file.write2SDFromMap("steeltalent", "comMap", comMap);
    							file.write2SDFromMap("steeltalent", "userMap", userMap);
                    		}
							msg.what = AppConstants.MsgStatus.MSG_SUCCUSS;
							mHander.sendMessage(msg);
						} catch (AppException e) {
							e.printStackTrace();
							msg.what = -1;
							msg.obj = e;
							mHander.sendMessage(msg);
						}
                    }

                }

            }

            @Override
            public void onStart() {
                //开始http请求的时候回调
                Log.i("vita", ">>>>>>>>..start..<<<<<<<<");
                //UToast.makeText(mContext, "开始加载", UToast.UToast_SHORT).show();
                Message msg = new Message();
                msg.what = AppConstants.MsgStatus.MSG_LOADING;
                mHander.sendMessage(msg);
            }

            @Override
            public void onFailure(Throwable t, String strMsg) {
                //加载失败的时候回调
                Log.i("vita", ">>>>>>>>....<<<<<<<<"
                        + strMsg);
                Message msg = new Message();
                msg.what = AppConstants.MsgStatus.MSG_ERROR;
                if(t instanceof  HttpResponseException){
                    msg.obj = AppException.http((HttpResponseException)t);
                    mHander.sendMessage(msg);
                }else{
                    msg.obj = AppException.http(new Exception("strMsg"));
                    mHander.sendMessage(msg);
                }

            }
        });
    }
    //分类Json数据处理
    private String[] resolveCategoryJson(String data) throws AppException{
    	String[] categoryInfos = null;
    	try {
			JSONObject jsonObject = new JSONObject(data);
			JSONArray resultArray = jsonObject.getJSONArray("index");
			categoryInfos = new String[resultArray.length()];
			for (int i = 0; i < resultArray.length(); i++) {
				String categoryInfo = resultArray.getString(i);
				categoryInfos[i] = categoryInfo;
			}
		} catch (Exception e) {
			throw AppException.http(e);
		}
    	return categoryInfos;
    }
    //行业资讯Json数据
    private ArrayList<NewsInfo> resolveNewsInfoJson(String data) throws AppException{
	    ArrayList<NewsInfo> newsInfoList = new ArrayList<NewsInfo>();
	    try {
			JSONObject jsonObject = new JSONObject(data);
			AppConfig.CURR_PAGE = jsonObject.getInt("page");
    		AppConfig.PAGE_COUNT = jsonObject.getInt("page_count");
			JSONArray resultArray = jsonObject.getJSONArray("result");
			for (int i = 0; i < resultArray.length(); i++) {
				NewsInfo newsInfo = new NewsInfo();
				JSONObject item = resultArray.getJSONObject(i);
				newsInfo.setNewsId(item.getInt("id"));
				newsInfo.setTitle(item.getString("title"));
				newsInfo.setDateTime(item.getString("datetime"));
				newsInfo.setDescription(item.getString("description"));
				
				newsInfoList.add(newsInfo);
			}
		} catch (Exception e) {
			throw AppException.http(e);
		}
	    return newsInfoList;
    }
    //应聘简历json数据处理
    private ArrayList<ResumeInfo> resolveResumeInfoJson(String data) throws AppException{
	    ArrayList<ResumeInfo> resumeInfoList = new ArrayList<ResumeInfo>();
	    try {
			JSONObject jsonObject = new JSONObject(data);
			AppConfig.CURR_PAGE = jsonObject.getInt("page");
    		AppConfig.PAGE_COUNT = jsonObject.getInt("page_count");
			JSONArray resultArray = jsonObject.getJSONArray("result");
			for (int i = 0; i < resultArray.length(); i++) {
				ResumeInfo resumeInfo = new ResumeInfo();
				JSONObject item = resultArray.getJSONObject(i);
				resumeInfo.setResumeId(item.getInt("id"));
				resumeInfo.setResumeName(item.getString("name"));
				resumeInfo.setJobType(item.getString("job_post"));
				resumeInfo.setSalary(item.getInt("salary"));
				resumeInfo.setType(item.getString("type"));
				resumeInfoList.add(resumeInfo);
			}
		} catch (Exception e) {
			throw AppException.http(e);
		}
	    return resumeInfoList;
    }
    //高级人才Json数据处理
    private ArrayList<TalentsInfo> resolveTalentsInfoJson (String data) throws AppException{
	    ArrayList<TalentsInfo> talentsInfoList = new ArrayList<TalentsInfo>();
	    try {
			JSONObject jsonObject = new JSONObject(data);
			AppConfig.CURR_PAGE = jsonObject.getInt("page");
    		AppConfig.PAGE_COUNT = jsonObject.getInt("page_count");
			JSONArray resultArray = jsonObject.getJSONArray("result");
			for (int i = 0; i < resultArray.length(); i++) {
				TalentsInfo talentsInfo = new TalentsInfo();
				JSONObject item = resultArray.getJSONObject(i);
				talentsInfo.setResumeId(item.getInt("id"));
				talentsInfo.setName(item.getString("name"));
				talentsInfo.setJobName(item.getString("job_post"));
				talentsInfo.setSalary(item.getInt("salary"));
				talentsInfoList.add(talentsInfo);
			}
		} catch (Exception e) {
			throw AppException.http(e);
		}
	    return talentsInfoList;
    }
    //招聘会场Json数据处理
    private ArrayList<JobFairInfo> resolveJobFairInfoJson (String data) throws AppException{
	    ArrayList<JobFairInfo> JobFairInfoList = new ArrayList<JobFairInfo>();
	    try {
			JSONObject jsonObject = new JSONObject(data);
			AppConfig.CURR_PAGE = jsonObject.getInt("page");
    		AppConfig.PAGE_COUNT = jsonObject.getInt("page_count");
			JSONArray resultArray = jsonObject.getJSONArray("result");
			for (int i = 0; i < resultArray.length(); i++) {
				JobFairInfo jobFairInfo = new JobFairInfo();
				JSONObject item = resultArray.getJSONObject(i);
				jobFairInfo.setJobFairId(item.getInt("id"));
				jobFairInfo.setTitle(item.getString("title"));
				jobFairInfo.setAddress(item.getString("address"));
				jobFairInfo.setOrganizers(item.getString("organizers"));
				JobFairInfoList.add(jobFairInfo);
			}
		} catch (Exception e) {
			throw AppException.http(e);
		}
	    return JobFairInfoList;
    }
    //热门企业Json数据处理
    private ArrayList<HotCompanyInfo> resolveHotCompanyInfoJson (String data) throws AppException{
	    ArrayList<HotCompanyInfo> HotCompanyInfoList = new ArrayList<HotCompanyInfo>();
	    try {
		JSONObject jsonObject = new JSONObject(data);
		AppConfig.CURR_PAGE = jsonObject.getInt("page");
		AppConfig.PAGE_COUNT = jsonObject.getInt("page_count");
		JSONArray resultArray = jsonObject.getJSONArray("result");
		for (int i = 0; i < resultArray.length(); i++) {
			HotCompanyInfo companyInfo = new HotCompanyInfo();
			JSONObject item = resultArray.getJSONObject(i);
			companyInfo.setCompanyId(item.getInt("uid"));
			companyInfo.setCompanyName(item.getString("name"));
			companyInfo.setAddress(item.getString("address"));
			HotCompanyInfoList.add(companyInfo);
		}
	} catch (Exception e) {
		throw AppException.http(e);
	}
	    return HotCompanyInfoList;
    }
    //招聘信息json数据处理
    private ArrayList<JobOfferInfo> resolveJobOfferInfoJson (String data) throws AppException{
	    ArrayList<JobOfferInfo> JobOfferInfoList = new ArrayList<JobOfferInfo>();
	    
	    try {
		JSONObject jsonObject = new JSONObject(data);
		AppConfig.CURR_PAGE = jsonObject.getInt("page");
		AppConfig.PAGE_COUNT = jsonObject.getInt("page_count");
		JSONArray resultArray = jsonObject.getJSONArray("result");
		for (int i = 0; i < resultArray.length(); i++) {
			JobOfferInfo jobInfo = new JobOfferInfo();
			JSONObject item = resultArray.getJSONObject(i);
			jobInfo.setJobId(item.getInt("id"));
			jobInfo.setCompanyId(item.getInt("uid"));
			jobInfo.setName(item.getString("name"));
			jobInfo.setClassification(item.getString("job1_son"));
			jobInfo.setSalary(item.getInt("salary"));
			jobInfo.setProvinceId(item.getInt("provinceid"));
			jobInfo.setCityId(item.getInt("cityid"));
			JobOfferInfoList.add(jobInfo);
		}
	} catch (Exception e) {
		throw AppException.http(e);
	}
	    
	    return JobOfferInfoList;
    }
    //热门搜索关键词json数据处理
    private String[] resolveHotKeyJson(String data) throws AppException{
	   String[] hotKey = null;
	   try {
		JSONObject jsonObject  = new JSONObject(data);
		hotKey = new String[jsonObject.length()];
		for(int i = 0 ; i < jsonObject.length();i++){
			
			hotKey[i] = jsonObject.getString(i+"");
		}
		
	} catch (Exception e) {
		
		throw AppException.http(e);
	}
	   return hotKey;
    }
    
    
    //推荐职位
    private ArrayList<RecommendedJobsInfo> resolveFeaturedJobsJson(String data) throws AppException {
        ArrayList<RecommendedJobsInfo> list =  new ArrayList<RecommendedJobsInfo>();
        try {
    		JSONObject jsonObject = new JSONObject(data);
    		AppConfig.CURR_PAGE = jsonObject.getInt("page");
    		AppConfig.PAGE_COUNT = jsonObject.getInt("page_count");
    		JSONArray resultArray = jsonObject.getJSONArray("result");
    		for (int i = 0; i < resultArray.length(); i++) {
    			RecommendedJobsInfo jobInfo = new RecommendedJobsInfo();
    			JSONObject item = resultArray.getJSONObject(i);
    			jobInfo.setJobId(item.getInt("id"));
    			jobInfo.setuId(item.getInt("uid"));
    			jobInfo.setName(item.getString("name"));
    			jobInfo.setJobSon(item.getString("job1_son"));
    			jobInfo.setSalary(item.getInt("salary"));
    			jobInfo.setProvinceId(item.getInt("provinceid"));
    			jobInfo.setCityId(item.getString("cityid"));
    			list.add(jobInfo);
    			
    		}
    	} catch (Exception e) {
    		throw AppException.http(e);
    	}
        return list;
    }

    /**
     * 保存地区Map到内存中
     * @param data
     * @param key
     * @throws AppException
     */
    public void saveAreaMap(String data, String key) throws AppException {
        try {
            if (AppConfig.areaMap.size() == 0) {
                JSONObject jsonObject = new JSONObject(data);
                JSONObject areaJson = jsonObject.getJSONObject(key);
                for(int i = 1 ; i < areaJson.length() ; i++){
                	JSON.parseObject(areaJson.toString(), new TypeReference<Map<String, String>>() {});
                    String o = areaJson.getString(i + "");
                    AppConfig.areaMap.put(i,o);
                }
              //  DebugUtil.Log(this,AppConfig.areaMap.toString());
            }
        } catch (Exception e) {
            throw AppException.http(e);
        }
    }
    /**
     * 将json数组转换成Map对象
     * 
     */
    public HashMap<String, String> getMapFromJson(String jsonString,String objectName) throws AppException
   {
	   JSONObject jsonObject;
	   try
	   {
		JSONObject JsonData = new JSONObject(jsonString);
	    jsonObject = JsonData.getJSONObject(objectName);
	    Iterator keyIter = jsonObject.keys();
	    String key;
	    String value;
	    HashMap<String, String> valueMap = new HashMap<String, String>();
	    while (keyIter.hasNext())
	    {
	     key = (String) keyIter.next();
	     value = (String) jsonObject.get(key);
	     valueMap.put(key, value);
	    }
	    return valueMap;
	   }
	   catch (JSONException e)
	   {
	    e.printStackTrace();
	   }
	   return null;
	 }

}
